import { defineStore } from "pinia";

// 判断运行环境
const isDev = process.env.NODE_ENV === "development";
const isH5 = process.env.UNI_PLATFORM === "h5";

// 存储key
const STORAGE_KEY = "user";

// 从localStorage获取数据
const getStorageData = () => {
  try {
    const data = localStorage.getItem(STORAGE_KEY);
    return data ? JSON.parse(data) : null;
  } catch (e) {
    console.error("获取存储数据失败:", e);
    return null;
  }
};

// 保存数据到localStorage
const saveStorageData = (data) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    console.log("保存数据成功:", data);
  } catch (e) {
    console.error("保存数据失败:", e);
  }
};

// H5端存储实现
const h5Storage = {
  getItem: (key) => {
    try {
      // 优先从localStorage获取
      let value = localStorage.getItem(key);
      if (!value) {
        // 如果localStorage没有，尝试从sessionStorage获取
        value = sessionStorage.getItem(key);
      }
      console.log("H5获取存储数据:", { key, value });
      return value ? JSON.parse(value) : null;
    } catch (e) {
      console.error("H5 storage getItem error:", e);
      return null;
    }
  },
  setItem: (key, value) => {
    try {
      // 同时存储到localStorage和sessionStorage
      const stringValue = JSON.stringify(value);
      localStorage.setItem(key, stringValue);
      sessionStorage.setItem(key, stringValue);
      console.log("H5存储数据成功:", { key, value });
    } catch (e) {
      console.error("H5 storage setItem error:", e);
    }
  },
};

// 文件系统存储实现（App端）
const fileSystemStorage = {
  getItem: (key) => {
    return new Promise((resolve, reject) => {
      plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
        fs.root.getFile(
          key,
          { create: false },
          (fileEntry) => {
            fileEntry.file((file) => {
              const reader = new plus.io.FileReader();
              reader.onloadend = (e) => {
                const result = JSON.parse(e.target.result);
                console.log("App获取存储数据:", { key, value: result });
                resolve(result);
              };
              reader.onerror = (e) => {
                console.error("App storage getItem error:", e);
                reject(e);
              };
              reader.readAsText(file);
            });
          },
          (error) => {
            console.log("App存储文件不存在:", { key });
            resolve(null);
          }
        );
      });
    });
  },
  setItem: (key, value) => {
    return new Promise((resolve, reject) => {
      plus.io.requestFileSystem(plus.io.PRIVATE_DOC, (fs) => {
        fs.root.getFile(key, { create: true }, (fileEntry) => {
          fileEntry.createWriter((writer) => {
            writer.onwrite = () => {
              console.log("App存储数据成功:", { key, value });
              resolve();
            };
            writer.onerror = (e) => {
              console.error("App storage setItem error:", e);
              reject(e);
            };
            writer.write(
              new Blob([JSON.stringify(value)], { type: "text/plain" })
            );
          });
        });
      });
    });
  },
};

// 开发环境存储实现
const devStorage = {
  getItem: (key) => {
    const value = uni.getStorageSync(key);
    console.log("开发环境获取存储数据:", { key, value });
    return value;
  },
  setItem: (key, value) => {
    uni.setStorageSync(key, value);
    console.log("开发环境存储数据成功:", { key, value });
  },
};

// 根据环境选择存储策略
const getStorageStrategy = () => {
  // 在浏览器环境中，始终使用H5存储

  if (typeof window !== "undefined" && window.localStorage) {
    console.log("使用H5存储策略");
    return h5Storage;
  }

  if (isDev) {
    console.log("使用开发环境存储策略");
    return devStorage;
  }

  console.log("使用App存储策略");
  return fileSystemStorage;
};

export const useUserStore = defineStore("user", {
  state: () => {
    // 初始化时从localStorage获取数据
    const storageData = getStorageData();
    return {
      loginToken: storageData?.loginToken || "",
      refreshToken: storageData?.refreshToken || "",
      userInfo: storageData?.userInfo || null,
    };
  },
  actions: {
    setToken(token) {
      console.log("设置token:", token);
      this.loginToken = token;
      // 保存到localStorage
      const currentData = getStorageData() || {};
      currentData.loginToken = token;
      saveStorageData(currentData);
    },
    setRefreshToken(token) {
      console.log("设置refreshToken:", token);
      this.refreshToken = token;
      // 保存到localStorage
      const currentData = getStorageData() || {};
      currentData.refreshToken = token;
      saveStorageData(currentData);
    },
    setUserInfo(info) {
      console.log("设置用户信息:", info);
      this.userInfo = info;
      // 保存到localStorage
      const currentData = getStorageData() || {};
      currentData.userInfo = info;
      saveStorageData(currentData);
    },
    clearUserInfo() {
      console.log("清除用户信息");
      this.loginToken = "";
      this.refreshToken = "";
      this.userInfo = null;
      // 清除localStorage
      localStorage.removeItem(STORAGE_KEY);
    },
  },
});
